/**
 * Created by yongwang on 2015/6/15.
 */
var scoreShopService = require('../../services/backoffice/backOffice-scoreShopService');
//var async = require('async');
var messageUtil = require('../../common/utils/messageUtil');
var toolUtil = require('../../common/utils/toolUtil');
var mysqlUtil = require('../../common/utils/mysqlUtil');


exports.changeStatus = function(req, res){
    var input = req.body,
        map = {
            id: input.id,
            status: input.status
        };
    logger.info(input);
    scoreShopService.changeStatus(map,function (err, result) {
        if (err) {
            logger.error('Exception happened when changeStatus...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when changeStatus...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, null));
        }
    });
};


exports.getScoreShopList = function (req, res) {
    var status = req.params.status;
    var page = req.params.page;
    scoreShopService.getScoreShopList(status, page, function (err, result) {
        if (err) {
            logger.error('Exception happened when getScoreShopList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getScoreShopList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.searchGoods = function (req, res) {
    var status = req.params.status;
    var name = req.params.name;
    scoreShopService.searchGoods(status, name, function (err, result) {

        if (err) {
            logger.error('Exception happened when searchGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchGoods...!' + err.message));

        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.addOneGoods = function(req, res){
    var input = req.body;

    toolUtil.uploadImageService(null, null, req, function (err, images) {
        if (err) {
            res.json(messageUtil.composeFailedMessage(req, 'Failed to upload Images... - ' + err.message));
        } else {
            var data = new Array();

            images.forEach(function (image) {
                if (image != null) {
                    data.push(image);
                }
            });

            input.inventoryLevel = Number(input.inventoryLevel);
            input.price = Number(input.price);
            input.cId = Number(input.cId);
            input.images = data[0];
            input.status = 0;
            input.__type__ = 'com.neighborhoods.data.domain.score.ScoreShopEntity';
            logger.info(input);

            var ctime = Math.round(new Date().getTime()),sql;
            if(input.cId){
                sql = "UPDATE score_shop SET product_name = '"+ input.productName +"',product_desc = '"+ input.productDesc +"',inventory_level = '"+ input.inventoryLevel +"',price = '"+ input.price +"'"+ (input.images == undefined?"":",images = '"+input.images+"'")+",update_time = '"+ ctime +"' WHERE id = '"+input.cId+"'";
            }else{
                sql = "insert into score_shop (product_name,product_desc,inventory_level,price,images,status,create_time) values ('"+input.productName+"','"+input.productDesc+"','"+input.inventoryLevel+"','"+input.price+"','"+input.images+"','"+input.status+"','"+ ctime +"')";
            }
            logger.info(sql);
            mysqlUtil.query(sql, function (err, result) {
                    if (err) {
                        logger.error('Exception happened when changeStatus...!' + err.message);
                        res.json(messageUtil.composeFailedMessage(req, 'Exception happened when addOneGoods...!' + err.message));
                    } else {
                        res.json(messageUtil.composeSucceededMessage(req, null, null));
                    }
            });

        }
    })
};


exports.searchValue = function (req, res) {
    var input = req.body,
        map = {
            communityName: input.communityName,
            userName: input.userName
        };

    scoreShopService.searchValue(map,function (err, result) {
        if (err) {
            logger.error('Exception happened when searchGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchGoods...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

//��ְ�С������
exports.getCommunityScoreList = function (req, res) {
    var map = {
        communityName: req.params.communityName,
        page: req.params.page
    };
    scoreShopService.getCommunityScoreList(map,function (err, result) {
        if (err) {
            logger.error('Exception happened when getCommunityScoreList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getCommunityScoreList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

//��Ʒ�һ�����
exports.searchExchangeGoods = function (req, res) {
    var input = req.body,
        map = {
            name: input.name,
            status: input.status,
            pageNum: input.pageNum,
            username :input.username
        };
    logger.debug(map);
    scoreShopService.searchExchangeGoods(map,function (err, result) {
        if (err) {
            logger.error('Exception happened when searchExchangeGoods...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchExchangeGoods...!' + err.message));
        } else {
            var data = result;

            scoreShopService.searchExchangeGoodsCount(map,function (err, result) {

                if (err) {
                    logger.error('Exception happened when searchExchangeGoodsCount...!' + err.message);
                    res.json(messageUtil.composeFailedMessage(req, 'Exception happened when searchExchangeGoodsCount...!' + err.message));
                } else {

                    logger.debug(result[0].pages);
                    //logger.debug(result.data.pages);
                    //logger.debug(data);
                    var temp = {
                        pages: Math.ceil(Number(result[0].pages) / 20),
                        recordList: data
                    };

                    res.json(messageUtil.composeSucceededMessage(req, null, temp));
                }

            });



        }
    });
};

exports.getUserScoreList = function (req, res) {
    var userId = req.params.userId;
    scoreShopService.getUserScoreList(userId,function (err, result) {
        if (err) {
            logger.error('Exception happened when getUserScoreList...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getUserScoreList...!' + err.message));
        } else {
            res.json(messageUtil.composeSucceededMessage(req, null, result));
        }
    });
};

exports.getAllCommunityStats = function (req, res) {
    var communityId = req.params.communityId;
    var startDate = req.params.startDate;
    var endDate = req.params.endDate;

    scoreShopService.getAllCommunityStats(communityId,startDate,endDate, function (err, result) {
        if (err) {
            logger.error('Exception happened when getAllCommunityStats...!' + err.message);
            res.json(messageUtil.composeFailedMessage(req, 'Exception happened when getAllCommunityStats...!' + err.message));
        } else {
            var data = {
                community: communityId,
                communityName: result[0] || communityId,
                scoreGained : result[1] || 0,
                scoreConsumed : result[2] || 0,
                currentScore: result[3] || 0
            }
            res.json(messageUtil.composeSucceededMessage(req, null, data));
        }
    });
};
